package org.visionlibrary.image.errors;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.model.ImageProcessingError;


public class MeanSquareError implements ImageProcessingError {
	@Override
	public float calculateError(TiledImage orig, TiledImage proc) {
		if (orig.getWidth() != proc.getWidth())
			return -1; // TODO rzucac wyjatkiem

		if (orig.getHeight() != proc.getHeight())
			return -1;

		if (orig.getNumBands() != proc.getNumBands())
			return -1;

		int maxX = orig.getWidth();
		int maxY = orig.getHeight();
		int channels = orig.getNumBands();

		float[] sums = new float[orig.getNumBands()];

		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++)
				for (int b = 0; b < channels; b++) {
					float origp = orig.getSampleFloat(x, y, b);
					float procp = proc.getSampleFloat(x, y, b);
					float diff = origp - procp;
					sums[b] = diff * diff;
				}

		float sum = 0;
		for (int i = 0; i < channels; i++)
			sum += sums[i] / (maxX * maxY);

		return sum / channels;
	}

}
